
from flask import Flask, request, jsonify
from flask_cors import CORS
import datetime

app = Flask(__name__)
CORS(app)

db = {
    "users": [{"workerId": "123456", "password": "123456", "name": "王医生"}],
    "patients": {
        "123456": {
            "caseId": "123456",
            "name": "张三",
            "assessScore": 78,
            "rehabDay": 12,
            "progressPct": 42,
            "risk": "中级",
            "plan": [
                "上肢主动关节活动 15min × 2",
                "坐立转移训练 10min × 2",
                "步行训练（助行器） 8min × 3",
                "呼吸肌训练 5min × 2",
            ],
            "bloodPressure": {"sbp": 128, "dbp": 82},
            "mobility": {"FMA": 58, "Berg": 36, "6MWT": 180},
            "caseNotes": [
                {"id": "n1", "content": "入院第12天，肌力较入院提高一级。",
                 "createdAt": "2025-10-25T09:10:00Z"}
            ],
            "reports": [
                {"id": "r1", "title": "头颅CT复查",
                 "content": "未见新梗灶，低密度灶略有吸收。",
                 "createdAt": "2025-10-24T14:20:00Z"}
            ],
            "updatedAt": "2025-10-25T14:45:00Z",
        }
    },
}

@app.route("/api/login", methods=["POST"])
def login():
    data = request.json or {}
    wid, pwd = data.get("workerId"), data.get("password")
    for user in db["users"]:
        if user["workerId"] == wid and user["password"] == pwd:
            return jsonify({"ok": True, "name": user["name"], "workerId": wid})
    return jsonify({"ok": False, "message": "工号或密码错误"}), 401

@app.route("/api/patient/<case_id>", methods=["GET"])
def get_patient(case_id):
    p = db["patients"].get(case_id)
    if not p:
        return jsonify({"ok": False, "message": "未找到该病例号"}), 404
    return jsonify({"ok": True, "data": p})

@app.route("/api/patient/<case_id>/note", methods=["POST"])
def add_note(case_id):
    p = db["patients"].get(case_id)
    if not p:
        return jsonify({"ok": False, "message": "未找到该病例号"}), 404
    content = (request.json or {}).get("content", "").strip()
    if not content:
        return jsonify({"ok": False, "message": "内容不能为空"}), 400
    item = {
        "id": str(datetime.datetime.utcnow().timestamp()),
        "content": content,
        "createdAt": datetime.datetime.utcnow().isoformat() + "Z",
    }
    p["caseNotes"].insert(0, item)
    return jsonify({"ok": True, "data": item})

@app.route("/api/patient/<case_id>/report", methods=["POST"])
def add_report(case_id):
    p = db["patients"].get(case_id)
    if not p:
        return jsonify({"ok": False, "message": "未找到该病例号"}), 404
    body = request.json or {}
    title = body.get("title", "未命名报告")
    content = body.get("content", "").strip()
    item = {
        "id": str(datetime.datetime.utcnow().timestamp()),
        "title": title,
        "content": content,
        "createdAt": datetime.datetime.utcnow().isoformat() + "Z",
    }
    p["reports"].insert(0, item)
    return jsonify({"ok": True, "data": item})

@app.route("/api/patients", methods=["GET"])
def list_patients():
    return jsonify({"ok": True, "data": list(db["patients"].values())})

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5000, debug=True)
